<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <el-form
      :model="queryForm"
      ref="queryForm"
      :rules="queryFormRules"
      size="small"
      :inline="true"
      style="margin-top: 8px"
      class="globalSerchFormStyle"
    >
      <el-row type="flex" justify="start" style="flex-wrap: wrap">
        <el-col :span="8">
          <el-form-item label="手机号" prop="phone" label-width="70px">
            <el-input
              v-model="queryForm.phone"
              placeholder="请输入"
              clearable
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="标签" label-width="80px">
            <el-select
              v-model="queryForm.labelId"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in labelList"
                :label="item.labelName"
                :value="item.id"
                :key="item.id"
              >
                {{ item.labelName }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item
            label="最后一笔充值时间"
            prop="chargeDateRange"
            label-width="130px"
          >
            <el-date-picker
              v-model="searchParams.chargeDateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 190px"
              value-format="yyyy-MM-dd HH:mmss"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="最后一笔消费时间"
            prop="consumeDateRange"
            label-width="130px"
          >
            <el-date-picker
              v-model="searchParams.consumeDateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 190px"
              value-format="yyyy-MM-dd HH:mmss"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-row>
            <el-col :span="14">
              <el-form-item
                label="充值次数"
                label-width="80px"
                prop="rStartCountNum"
              >
                <el-input
                  type="text"
                  maxlength="11"
                  show-word-limit
                  placeholder="请输入"
                  v-model="queryForm.rStartCountNum"
                >
                  <span slot="append">次</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">~</el-col>
            <el-col :span="9">
              <el-form-item prop="rEndCountNum">
                <el-input
                  type="text"
                  maxlength="11"
                  show-word-limit
                  placeholder="请输入"
                  v-model="queryForm.rEndCountNum"
                >
                  <span slot="append">次</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row>
            <el-col :span="14">
              <el-form-item
                label="加油次数"
                label-width="80px"
                prop="startCountNum"
              >
                <el-input
                  placeholder="请输入"
                  v-model="queryForm.startCountNum"
                  type="text"
                  maxlength="11"
                  show-word-limit
                >
                  <span slot="append">次</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">~</el-col>
            <el-col :span="9">
              <el-form-item prop="endCountNum">
                <el-input
                  placeholder="请输入"
                  v-model="queryForm.endCountNum"
                  type="text"
                  maxlength="11"
                  show-word-limit
                >
                  <span slot="append">次</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row>
            <el-col :span="14">
              <el-form-item label="加油金额" label-width="70px" prop="startAmt">
                <el-input
                  placeholder="请输入"
                  v-model="queryForm.startAmt"
                  type="text"
                  maxlength="11"
                  show-word-limit
                >
                  <span slot="append">元</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">~</el-col>
            <el-col :span="9">
              <el-form-item prop="endAmt">
                <el-input
                  placeholder="请输入"
                  v-model="queryForm.endAmt"
                  type="text"
                  maxlength="11"
                  show-word-limit
                >
                  <span slot="append">元</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row>
            <el-col :span="14">
              <el-form-item
                label="加油数量"
                label-width="80px"
                prop="startLiters"
              >
                <el-input
                  placeholder="请输入"
                  v-model="queryForm.startLiters"
                  clearable
                  type="text"
                  maxlength="11"
                  show-word-limit
                >
                  <span slot="append">(L/kg)</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">~</el-col>
            <el-col :span="9">
              <el-form-item prop="endLiters">
                <el-input
                  placeholder="请输入"
                  v-model="queryForm.endLiters"
                  clearable
                  type="text"
                  maxlength="11"
                  show-word-limit
                >
                  <span slot="append">(L/kg)</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <!-- 按钮 -->
    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          type="primary"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="primary"
          @click="handleIssuanceVouchers({}, 'patch')"
          :disabled="current_select_rows.length === 0"
          >批量发券</el-button
        >
      </el-col>
    </el-row>
    <!-- <div class="card card-body">
      <div class="container">
        <div class="row">
          <div class="col-sm col-md-3 offset-md-1">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px"></div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">油品：</span>
              </div>
              <select
                class="custom-select"
                id="inputGroupSelect01"
                style="width: 80px"
                v-model="queryParams.oilName"
              >
                <option :value="undefined" selected>全部</option>
                <option
                  :value="ele.oilId"
                  v-for="ele in oilList"
                  :key="ele.oilName"
                >
                  {{ ele.oilClass + "-" + ele.oilType + "-" + ele.oilName }}
                </option>
              </select>
            </div>
          </div>
          <div class="col-sm col-md-7"></div>
        </div>
        <div class="row">
          <div class="col-sm col-md-3 offset-md-1">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px"></div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">标签：</span>
              </div>
              <select
                class="custom-select"
                id="inputGroupSelect01"
                style="width: 80px"
                v-model="queryParams.labelId"
              >
                <option :value="undefined" selected>全部</option>
                <option :value="ele.id" v-for="ele in labelList" :key="ele.id">
                  {{ ele.labelName }}
                </option>
              </select>
            </div>
          </div>
          <div class="col-sm col-md-8">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px"></div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">日期：</span>
                <el-date-picker
                  v-model="searchParams.data"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  size="mini"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="margin-top: 2px; max-width: 350px"
                >
                </el-date-picker>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-sm col-md-9 offset-md-1">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px"></div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping"
                  >加油频率：</span
                >
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.startCountNum"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">次</span>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">
                  &lt; 加油次数 &lt;
                </span>
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.endCountNum"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">次</span>
              </div>
            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-sm col-md-9 offset-md-1">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px">
                <select
                  class="custom-select custom-select-sm"
                  id="inputGroupSelect01"
                  v-model="queryParams.amtFlag"
                >
                  <option value="1">或者</option>
                  <option value="2">并且</option>
                </select>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping"
                  >加油金额：</span
                >
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.startAmt"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">元</span>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">
                  &lt; 加油金额 &lt;
                </span>
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.endAmt"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">元</span>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-sm col-md-9 offset-md-1">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px">
                <select
                  class="custom-select custom-select-sm"
                  id="inputGroupSelect01"
                  v-model="queryParams.litersFlag"
                >
                  <option value="1">或者</option>
                  <option value="2">并且</option>
                </select>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping"
                  >数量(L/kg)(L/kg)</span
                >
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.startLiters"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">(L/kg)</span>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">
                  &lt; 数量(L/kg) &lt;
                </span>
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.endLiters"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">(L/kg)</span>
              </div>
            </div>
          </div>
        </div>
        <div class="row mb-0 mt-3" v-show="queryParams.secondFlag == 0">
          <div class="col-sm-4 offset-sm-3">
            <el-button
              type="info"
              size="mini"
              icon="el-icon-arrow-down"
              data-toggle="collapse"
              data-target="#collapseExample"
              aria-expanded="false"
              aria-controls="collapseExample"
              @click="toggleQuery"
              >展开查询</el-button
            >
          </div>
          <div class="col-sm-4">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-search"
              @click="getList"
              >立刻查询</el-button
            >
          </div>
        </div>
      </div>

      <div class="container collapse" id="collapseExample">
        <hr />
        <div class="row">
          <div class="col-sm col-md-8 offset-md-1">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px"></div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">时间：</span>
                <el-date-picker
                  v-model="searchParams.secondDate"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  size="mini"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="margin-top: 2px; max-width: 350px"
                >
                </el-date-picker>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-sm col-md-9 offset-md-1">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px"></div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping"
                  >加油频率：</span
                >
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model="queryParams.secondStartCountNum"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">次</span>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping"
                  >&lt; 加油次数 &lt;=</span
                >
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model="queryParams.secondEndCountNum"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">次</span>
              </div>
            </div>
          </div>
        </div>

        <div class="row">
          <div class="col-sm col-md-9 offset-md-1">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px">
                <select
                  class="custom-select custom-select-sm"
                  id="inputGroupSelect01"
                  v-model="queryParams.secondAmtFlag"
                >
                  <option value="1">或者</option>
                  <option value="2">并且</option>
                </select>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping"
                  >加油金额：</span
                >
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.secondStartAmt"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">元</span>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">
                  &lt; 加油金额 &lt;=
                </span>
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.secondEndAmt"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">元</span>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-sm col-md-9 offset-md-1">
            <div class="input-group input-group-sm flex-nowrap">
              <div class="input-group-prepend" style="width: 80px">
                <select
                  class="custom-select custom-select-sm"
                  id="inputGroupSelect01"
                  v-model="queryParams.secondLitersFlag"
                >
                  <option value="1">或者</option>
                  <option value="2">并且</option>
                </select>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping"
                  >数量(L/kg)(L/kg)</span
                >
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.secondStartLiters"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">(L/kg)</span>
              </div>
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping"
                  >&lt; 数量(L/kg) &lt;=</span
                >
              </div>
              <input
                type="text"
                class="form-control"
                aria-label="Username"
                aria-describedby="addon-wrapping"
                v-model.number="queryParams.secondEndLiters"
              />
              <div class="input-group-prepend">
                <span class="input-group-text" id="addon-wrapping">(L/kg)</span>
              </div>
            </div>
          </div>
        </div>
        <div class="row mb-0 mt-3" v-show="queryParams.secondFlag == 1">
          <div class="col-sm-4 offset-sm-3">
            <el-button
              type="info"
              size="mini"
              icon="el-icon-arrow-up"
              data-toggle="collapse"
              data-target="#collapseExample"
              aria-expanded="false"
              aria-controls="collapseExample"
              @click="toggleQuery"
              >展开查询</el-button
            >
          </div>
          <div class="col-sm-4">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-search"
              @click="getList"
              >立刻查询</el-button
            >
          </div>
        </div>
      </div>
    </div> -->
    <el-table
      :data="userList"
      v-loading="loading"
      @selection-change="selectionChange"
      stripe
    >
      <af-table-column align="left" prop="id" type="selection" />

      <af-table-column label="标签" align="left" prop="labelName" />
      <af-table-column label="用户姓名" align="left" prop="customerName" />
      <!--
      <af-table-column label="当前归属的标签" align="left" prop="labelName">
        <template slot-scope="scope">
          <span
            class="badge"
            :class="[
              scope.row.labelId === null ? 'badge-danger' : 'badge-success',
            ]"
          >
            {{
              scope.row.labelId === null ? "未标记" : scope.row.labelName
            }}</span
          >
        </template>
      </af-table-column>
      -->
      <af-table-column label="手机号" align="left" prop="phone" />
      <af-table-column
        label="最后一笔充值时间"
        align="left"
        prop="rCreateDate"
      />
      <af-table-column
        label="最后一笔消费时间"
        align="left"
        prop="createDate"
      />

      <af-table-column
        label="近期充值详细"
        align="left"
        prop="stationName"
        width="160px"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-search"
            class="underline btn24"
            size="mini"
            @click="getCharge(scope.row)"
            >查看</el-button
          >
        </template>
      </af-table-column>

      <af-table-column
        label="近期消费详细"
        align="left"
        prop="stationName"
        width="160px"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-search"
            class="underline btn24"
            size="mini"
            @click="getConsume(scope.row)"
            >查看</el-button
          >
        </template>
      </af-table-column>
      <af-table-column label="操作" align="left" width="160px" fixed="right">
        <template slot-scope="scope">
          <!--
          <el-dropdown @command="toLabeled">
            <span class="el-dropdown-link" style="font-size: 12px">
              打标签<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                :command="ele.id + '.' + scope.row.phone"
                v-for="ele in labelList"
                :key="ele.id"
                >{{ ele.labelName }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
          -->
          <!-- <el-button
            type="text"
            icon="el-icon-circle-plus-outline"
            class="underline btn24"
            size="mini"
            slot="reference"
            @click="openSendMessage(scope.row)"
            >推送消息</el-button
          > -->
          <el-button
            type="text"
            class="underline btn24"
            size="mini"
            @click="handleIssuanceVouchers(scope.row, 'single')"
            >发券</el-button
          >
          <!--
          <el-popconfirm
            title="此操作会将选中用户强制列为无标签状态，是否继续？"
            confirm-button-text="删除"
            @onConfirm="toUnLableed(scope.row)"
          >
          
            <el-button
              type="text"
              icon="el-icon-circle-plus-outline"
              class="underline btn24"
              size="mini"
              slot="reference"
              >删标签</el-button
            >
          </el-popconfirm>
          -->
        </template>
      </af-table-column>
    </el-table>
    <el-pagination
      class="fr"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />

    <!-- 消费明细 -->
    <el-drawer
      title="消费详细"
      :visible.sync="orderDialog"
      direction="rtl"
      size="50%"
      custom-class="add-drawer"
    >
      <div class="app-container">
        <el-table :data="orderList" v-loading="orderLoading" border>
          <!-- <af-table-column label="油站" align="left" prop="stationName" /> -->
          <af-table-column label="订单号" align="left" prop="orderNo" />
          <af-table-column label="油品名称" align="left" prop="oilName" />
          <af-table-column label="油品价格" align="left" prop="oilPirce" />
          <af-table-column label="数量(L/kg)" align="left" prop="orderLiters" />
          <af-table-column label="实付金额(元)" align="left" prop="amt" />
          <!-- <af-table-column label="加油枪号" align="left" prop="oilGun" /> -->
          <af-table-column
            label="支付完成时间"
            align="left"
            prop="payDate"
            width="160px"
          >
            <template slot-scope="scope">
              <span>{{
                parseTime(scope.row.payDate, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </af-table-column>
        </el-table>
        <pagination
          v-show="orderList.length > 0"
          :total="orderTotal"
          :page.sync="orderQuery.pageNum"
          :limit.sync="orderQuery.pageSize"
          @pagination="getOrderList"
        />
        <el-button
          type="primary"
          size="medium"
          style="float: right; margin-top: 20px"
          @click="orderDialog = false"
          >返回</el-button
        >
      </div>
    </el-drawer>

    <!-- 推送消息 -->
    <el-dialog
      title="推送消息"
      :visible.sync="messageOpenDialog"
      width="750px"
      @close="messageOpenDialogClose"
      append-to-body
    >
      <el-form
        :model="messageForm"
        ref="messageForm"
        :rules="messageRules"
        size="medium"
        label-width="100px"
      >
        <el-form-item
          prop="id"
          label="发放的模板"
          :rules="{
            required: true,
            message: '请选择发放方式',
            trigger: 'change',
          }"
        >
          <el-select
            v-model="messageForm.id"
            clearable
            placeholder="请选择发放方式"
          >
            <el-option
              :label="ele.issueRemark + ' - ' + ele.issueName"
              :value="ele.id"
              :key="ele.id"
              v-for="ele in issueList"
            ></el-option>
          </el-select>
          <div style="font-size: 12px; color: #727a85">
            此处拉取类型为 [网页方式、二维码] 的发放方式
          </div>
        </el-form-item>
        <el-form-item
          label="发放的消息"
          prop="message"
          :rules="{
            required: true,
            message: '请选择发放的消息',
            trigger: 'change',
          }"
        >
          <!-- <el-input
            placeholder="请输入要推送的消息"
            clearable
            v-model="messageForm.message"
          /> -->
          <el-input
            v-model="messageForm.message"
            type="textarea"
            placeholder="请输入要推送的内容"
            :autosize="{ minRows: 4, maxRows: 4 }"
            :style="{ width: '100%' }"
          >
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handleSubmitMessage"
          size="small"
          :loading="sendLoading"
          :disabled="sendLoading"
          >确 定 发 送</el-button
        >
        <el-button
          @click="cancelSubmitMessage"
          :disabled="sendLoading"
          size="small"
          >取 消</el-button
        >
      </div>
    </el-dialog>

    <!-- 充值明细 -->
    <CouponGrantRecentCharge
      :recentChargeDialog.sync="recentChargeDialog"
      :currentRowDataInfo="currentRowDataInfo"
    ></CouponGrantRecentCharge>

    <!-- 发券 -->
    <CouponGrantFormVue
      ref="CouponGrantFormVue"
      :parm="params"
      @getData="getData"
    />
  </div>
</template>

<script>
import {
  getLabelUser,
  getLabelList,
  delUserLabel,
  addAndDelCustomerLabel,
  getConsume,
  getOilNameList,
  drawCoupons,
} from "@/api/label/label";
import { listIssue, listForCoupon, creationList } from "@/api/coupon";

import { getOilListByLogin } from "@/api/dept";
import { sendMessageToUser, activeSendMessage } from "@/api/customer/manage";
import settings from "@/settings";
import Base64 from "@/utils/base64";
import CouponGrantFormVue from "./Coupon_Grant_form.vue";
import CouponGrantRecentCharge from "./Coupon_Grant_recentCharge";
import { cloneDeep } from "lodash";
export default {
  name: "Coupon_Grant",
  components: { CouponGrantFormVue, CouponGrantRecentCharge },
  data() {
    let validateMsg = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入推送的消息"));
        return;
      }
      const len = this.bytesLength(value);
      if (len > 28) {
        callback(new Error("输入的汉字数量(L/kg)不超过14"));
        return;
      }
      callback();
    };
    // 充值,加油次数---开始次数
    let check_start = (rule, value, callback) => {
      let val = Number(value.trim());
      let end;
      if (rule.field === "rStartCountNum") {
        end = this.queryParams.rEndCountNum;
      }
      if (rule.field === "startCountNum") {
        end = this.queryParams.endCountNum;
      }
      const pattern = /^\d+(\.\d{0,0})?$/; // 整数
      if (Number.isNaN(val)) return callback(new Error("请输入有效数值"));
      if (val < 0) return callback(new Error("不能小于0"));
      if (!pattern.test(val)) return callback(new Error("请输入整数"));
      if (end && val >= end) return callback(new Error("开始值应小于结束值"));
      this.queryParams[rule.field] = val;
      callback();
    };

    //  充值,加油次数---结束次数
    let check_end = (rule, value, callback) => {
      let end = Number(value.trim());
      let start;
      if (rule.field === "rEndCountNum") {
        start = this.queryParams.rStartCountNum;
      }
      if (rule.field === "endCountNum") {
        start = this.queryParams.startCountNum;
      }
      const pattern = /^\d+(\.\d{0,0})?$/; // 整数
      if (Number.isNaN(end)) return callback(new Error("请输入有效数值"));
      if (end <= 0) return callback(new Error("不能小于等于0"));
      if (!pattern.test(end)) return callback(new Error("请输入整数"));
      if (end <= start) return callback(new Error("结束值应大于开始值"));
      this.queryParams[rule.field] = end;
      callback();
    };

    // 加油金额(startAmt)，加油数量(startLiters)---开始值
    let check_start2 = (rule, value, callback) => {
      let start = Number(value.trim());
      let end;
      let pattern;
      if (rule.field === "startAmt") {
        pattern = /^\d+(\.\d{1,2})?$/; //  两位小数点
        end = this.queryParams.endAmt;
      }
      if (rule.field === "startLiters") {
        pattern = /^\d+(\.\d{1,4})?$/; //  4位小数点
        end = this.queryParams.endLiters;
      }
      if (Number.isNaN(start)) return callback(new Error("请输入有效数值"));
      if (start < 0) return callback(new Error("不能小于0"));
      if (!pattern.test(start))
        return rule.field === "startAmt"
          ? callback(new Error("最多两位小数点"))
          : callback(new Error("最多四位小数点"));
      if (end && start >= end)
        return callback(new Error("开始值不能大于结束值"));
      this.queryParams[rule.field] = start;
      callback();
    };

    // 加油金额，加油数量---结束值
    let check_end2 = (rule, value, callback) => {
      console.log("结束：", rule);
      let end = Number(value.trim());
      let pattern;
      let start;
      if (rule.field === "endAmt") {
        // 金额
        pattern = /^\d+(\.\d{1,2})?$/; //  两位小数点
        start = this.queryParams.startAmt;
      }
      if (rule.field === "endLiters") {
        pattern = /^\d+(\.\d{1,4})?$/; //  4位小数点
        start = this.queryParams.startLiters;
      }
      if (Number.isNaN(end)) return callback(new Error("请输入有效数值"));
      if (end <= 0) return callback(new Error("不能小于等于0"));
      if (!pattern.test(end))
        return rule.field === "endAmt"
          ? callback(new Error("最多两位小数点"))
          : callback(new Error("最多四位小数点"));

      if (start && start >= end)
        return callback(new Error("结束值应大于开始值"));
      this.queryParams[rule.field] = end;
      console.log(start, end);
      callback();
    };

    return {
      sendLoading: false,
      orderLoading: false,
      messageRules: {
        msg: [{ validator: validateMsg, trigger: "change" }],
      },
      messageOpenDialog: false,
      // 总条数
      total: 0,
      // 客户电子会员卡充值消费记录表格数据
      userList: [],
      searchParams: {
        data: null,
        secondDate: null,
        chargeDateRange: null, // 充值时间范围
        consumeDateRange: null, // 消费时间范围
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,

        oilName: null,
        labelId: null,

        beginDate: null,
        endDate: null,

        startCountNum: null,
        endCountNum: null,

        amtFlag: "1",
        startAmt: null,
        endAmt: null,

        litersFlag: "1",
        startLiters: null,
        endLiters: null,

        secondFlag: 0,
        secondBeginDate: null,
        secondEndDate: null,

        secondStartCountNum: null,
        secondEndCountNum: null,

        secondAmtFlag: "1",
        secondStartAmt: null,
        secondEndAmt: null,

        secondLitersFlag: "1",
        secondStartLiters: null,
        secondEndLiters: null,
        cardCodeFalg: "1",

        // 充值次数
        rStartCountNum: null,
        rEndCountNum: null,

        // 加油次数
        startCountNum: null,
        endCountNum: null,

        // 加油金额
        startAmt: null,
        endAmt: null,

        // 加油数量
        startLiters: null,
        endLiters: null,
      },
      orderList: [{}],
      orderOpen: false,
      totalInfo: 0,
      query: {
        pageNum: 1,
        pageSize: 10,
        unionId: null,
        customerName: null,
        recordType: null,
        integral: null,
        stationId: null,
        stationName: null,
        levelId: this.levelId,
      },
      dateRangeCreatedDate: [],
      selectedUser: [],
      checkedUser: [],
      toLabeledDialog: false,
      labelList: [],
      oilList: [],
      currentLabelId: undefined,
      orderDialog: false,
      orderTotal: 0,
      orderQuery: {
        pageNum: 1,
        pageSize: 10,
        customerPhone: undefined,
      },
      showQuery: false,
      messageForm: {
        message: "",
        codeList: [],
        id: "",
        url: "",
      },
      issueList: [],
      queryForm: {},
      queryFormRules: {
        rStartCountNum: [{ validator: check_start, trigger: "change" }],
        rEndCountNum: [{ validator: check_end, trigger: "change" }],
        startCountNum: [{ validator: check_start, trigger: "change" }],
        endCountNum: [{ validator: check_end, trigger: "change" }],
        startAmt: [{ validator: check_start2, trigger: "change" }],
        endAmt: [{ validator: check_end2, trigger: "change" }],
        startLiters: [{ validator: check_start2, trigger: "change" }],
        endLiters: [{ validator: check_end2, trigger: "change" }],
      },
      loading: false,
      page: 1,
      pageSize: 10,
      total: 0,
      params: {},
      recentChargeDialog: false,
      currentRowDataInfo: {}, // 单独发券选中行信息
      current_select_rows: [], // 当前选中的所有行
    };
  },
  computed: {},
  created() {
    this.getIssueList();
    // this.getList();
    this.getData();
    this.getLabelList();
    getOilListByLogin()
      .then((res) => {
        if (res.code == 200) {
          this.oilList = res.rows;
        } else {
          throw new Error("");
        }
      })
      .catch(() => {
        this.msgError("拉取油品列表失败，请刷新网页~");
      });
  },
  methods: {
    // 获取标签列表
    async getLabelList() {
      const res = await getLabelList();
      this.labelList = res.rows;
      console.log(res, "标签列表");
    },
    // 发券
    async handleIssuanceVouchers(row, action) {
      console.log("row--", row);
      let res = await creationList({ status: 1 });
      this.params = {
        drawerShow: true,
        drawerType: "add",
        // cardData: row,
        couponList: res.rows || [],
        couponGrantForm: {
          enterpriseId: this.presentEnterprise.enterpriseId,
          // mobilePhoneList: [row.phone],
          ccsdId: 0,
          sendFlag: 0, // 是否推送消息 0推送 1不推送
        },
      };
      if (action === "single") {
        console.log("单个发券");
        this.params.cardData = row;
        this.params.couponGrantForm.mobilePhoneList = [row.phone];
      }
      if (action === "patch") {
        console.log("批量发券");
        const phoneList = this.current_select_rows.map((item) => item.phone);
        this.params.cardData = this.current_select_rows;
        this.params.couponGrantForm.mobilePhoneList = phoneList;
      }
    },
    getData() {
      if (this.loading) return;
      this.loading = true;
      let queryData = this.getQueryData(this.queryForm);
      queryData = Object.assign(
        {
          pageNum: this.page,
          pageSize: this.pageSize,
        },
        queryData
      );

      if (
        this.searchParams.chargeDateRange &&
        this.searchParams.chargeDateRange.length
      ) {
        queryData.rBeginDate = this.searchParams.chargeDateRange[0];
        queryData.rEndDate = this.searchParams.chargeDateRange[1];
      }
      if (
        this.searchParams.consumeDateRange &&
        this.searchParams.consumeDateRange.length
      ) {
        queryData.beginDate = this.searchParams.consumeDateRange[0];
        queryData.endDate = this.searchParams.consumeDateRange[1];
      }

      listForCoupon(queryData).then((res) => {
        if (res && res.code === 200) {
          this.userList = res.rows;
          this.total = res.total;
        } else {
          this.userList = [];
          this.total = 0;
        }
      });
      this.loading = false;
    },
    getQueryData(data) {
      let queryData = data;
      Object.keys(queryData).forEach((key) => {
        if (queryData[key] === "" || queryData[key] === undefined) {
          queryData[key] = null;
        }
      });
      return queryData;
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getData();
    },
    handleIssueToURL(id) {
      const base64 = Base64.getInstance();
      const encodeStr = "i" + id;
      const encodedStr = base64.encode(encodeStr);
      const trimEqualStr = encodedStr.replace(/={1,}$/g, "");
      this.exportQrDialog = true;
      const text =
        settings.baseURL +
        this.presentEnterprise.enterpriseId +
        "/" +
        trimEqualStr;
      return text;
    },
    getIssueList() {
      listIssue({
        // 拉取发放方式
        pageNum: 1,
        pageSize: 1000,
        issueName: null,
        issueRemark: null,
        issueType: "2", // 网页类型
        status: "1", // 状态为启动
      })
        .then((res) => {
          // console.log('你好',res)
          if (res.code == 200) {
            if (res.rows == null) {
              this.issueList = [];
            } else {
              this.issueList = res.rows;
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("亲，拉取领取方式列表失败~");
        });
    },
    messageOpenDialogClose() {
      this.selectedUser = [];
    },
    openSendMessage(row) {
      if (this.selectedUser.length == 0) {
        this.selectedUser = [row];
      }
      this.messageOpenDialog = true;
    },

    // 近期消费明细
    getConsume(row) {
      this.orderQuery.customerPhone = row.phone;
      this.getOrderList();
    },

    // 近期充值明细
    getCharge(row) {
      console.log("获取充值充值明细");
      this.currentRowDataInfo = cloneDeep(row);
      this.recentChargeDialog = true;
    },

    getOrderList() {
      this.orderLoading = true;
      getConsume(this.orderQuery)
        .then((res) => {
          this.orderLoading = false;
          if (res.code == 200) {
            this.orderList = res.rows;
            this.orderTotal = res.total;
            this.orderDialog = true;
          } else {
            throw new Error("");
          }
        })
        .catch(() => {
          this.msgError("查询近日订单~");
        });
    },
    toLabeledDialogClose() {
      this.selectedUser = [];
      this.checkedUser = [];
    },
    handleSubmitMessage() {
      this.messageForm.url = this.handleIssueToURL(this.messageForm.id);
      this.$refs["messageForm"].validate((valid) => {
        if (valid) {
          const codeList = [];
          this.selectedUser.map((ele) => {
            codeList.push(ele.cardCode);
          });
          this.messageForm.codeList = codeList;
          this.sendLoading = true;
          console.log(this.messageForm);
          activeSendMessage(this.messageForm)
            .then((res) => {
              if (res.code == 200) {
                this.msgSuccess(res.msg);
              } else {
                throw new Error("");
              }
            })
            .catch(() => {
              this.msgError("发送失败~");
            })
            .finally(() => {
              this.sendLoading = false;
            });
        }
      });
    },
    cancelSubmitMessage() {
      this.messageOpenDialog = false;
    },
    handleSubmitLable() {
      const addArr = [];
      this.selectedUser.map((ele) => {
        if (ele.labelId != this.currentLabelId && !ele.labelId)
          addArr.push(ele.phone);
      });
      addAndDelCustomerLabel({
        labelId: this.currentLabelId,
        flag: "0",
        phoneList: addArr,
      })
        .then((res) => {
          if (res.code == 200) {
            this.getList();
            this.msgSuccess("批量拉入标签成功~");
            this.toLabeledDialog = false;
          } else {
            throw new Error("");
          }
        })
        .catch(() => {
          this.msgError("批量拉入标签失败，请刷新网页后重试~");
          this.toLabeledDialog = false;
        });
    },
    cancelSubmitLabel() {
      this.getList();
      this.toLabeledDialog = false;
    },
    translationLabel(id) {
      const label = this.labelList.find((ele) => {
        return id == ele.id;
      });
      if (label == undefined) {
        return "";
      }
      return label.labelName;
    },
    toUnLableed(row) {
      const delArr = [];
      if (this.selectedUser.length == 0) {
        delArr.push(row.phone);
      } else {
        this.selectedUser.map((ele) => {
          if (!!ele.phone) {
            delArr.push(ele.phone);
          }
        });
      }

      delUserLabel({ phoneList: delArr })
        .then((res) => {
          if (res.code == 200) {
            this.getList();
            this.msgSuccess("删除用户标签成功~");
          } else {
            throw new Error("");
          }
        })
        .catch(() => {
          this.msgError("删除用户标签状态失败，请刷新后重试~");
        });
    },
    toClearLabel(row) {
      const delArr = [];
      if (this.checkedUser.length == 0) {
        this.checkedUser = [row];
        delArr.push(row.phone);
      } else {
        this.checkedUser.map((ele) => {
          delArr.push(ele.phone);
        });
      }

      delUserLabel({ phoneList: delArr })
        .then((res) => {
          if (res.code == 200) {
            this.checkedUser.map((ele) => {
              if (delArr.includes(ele.phone)) {
                ele.labelId = null;
                ele.labelName = null;
              }
            });
            this.msgSuccess("删除用户标签成功~");
          } else {
            throw new Error("");
          }
        })
        .catch(() => {
          this.msgError("删除用户标签状态失败，请刷新后重试~");
        });
    },
    selectionChange(selection) {
      this.checkedUser = [];
      console.log("当前选中tbale行：", selection);
      this.selectedUser = selection;
      this.current_select_rows = selection;
    },
    checkChange(selection) {
      this.checkedUser = selection;
    },
    usageTypeFotmat(row, column) {
      if (row.usageType === "+") {
        return "充值";
      } else if (row.usageType === "-") {
        return "消费";
      }
    },
    cardOilsTypeFotmat(row, column) {
      if (row.cardOilsType === "1") {
        return "汽油";
      } else if (row.cardOilsType === "2") {
        return "柴油";
      } else if (row.cardOilsType === "3") {
        return "非油品";
      } else if (row.cardOilsType === "4") {
        return "LNG";
      } else if (row.cardOilsType === "5") {
        return "CNG";
      }
    },
    /** 查询客户电子会员卡充值消费记录列表 */
    getList() {
      if (this.searchParams.data === null) {
        this.queryParams.beginDate = null;
        this.queryParams.endDate = null;
      } else {
        this.queryParams.beginDate = this.searchParams.data[0];
        this.queryParams.endDate = this.searchParams.data[1];
      }
      if (this.searchParams.secondDate === null) {
        this.queryParams.secondBeginDate = null;
        this.queryParams.secondEndDate = null;
      } else {
        this.queryParams.secondBeginDate = this.searchParams.secondDate[0];
        this.queryParams.secondEndDate = this.searchParams.secondDate[1];
      }
      getLabelUser(this.queryParams).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
      });
    },
    handleQuery() {
      this.getData();
    },
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.searchParams = {
        chargeDateRange: null,
        consumeDateRange: null,
      };
      this.queryForm = {
        rStartCountNum: null,
        rEndCountNum: null,
        startCountNum: null,
        endCountNum: null,
        startAmt: null,
        endAmt: null,
        startLiters: null,
        endLiters: null,
      };

      this.getData();
    },
    orderOpenMethod() {
      this.orderOpen = true;
    },
    toLabeled(idAndPhone) {
      const idAndPhoneArr = idAndPhone.match(/\d{1,}/g);
      const id = idAndPhoneArr[0];
      const phone = idAndPhoneArr[1];

      if (!id || !phone) {
        this.msgError("打标签失败，刷新重试~");
        return;
      }

      if (this.selectedUser.length == 0) {
        const user = this.userList.find((ele) => {
          return ele.phone == phone;
        });
        if (user === undefined) {
          this.msgError("打标签失败，刷新重试~");
          return;
        }
        this.selectedUser = [user];
      }
      this.currentLabelId = id;
      this.toLabeledDialog = true;
    },
    toggleQuery() {
      if (this.queryParams.secondFlag == 0) {
        this.queryParams.secondFlag = 1;
      } else {
        this.queryParams.secondFlag = 0;
      }
    },
    bytesLength(str) {
      var count = str.length;
      for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 255) {
          count++;
        }
      }
      return count;
    },
  },
};
</script>
<style scoped lang="scss">
.globalSerchFormStyle {
  > .el-row {
    > .el-col {
      margin-bottom: 20px;
    }
  }
}
::v-deep .add-drawer {
  overflow-y: auto;
  .el-drawer__header {
    border-bottom: 1px solid #ddd;
    padding-bottom: 20px;
  }
}
.label_batch {
  .container {
    .row {
      margin-bottom: 10px;
    }
  }
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
